package com.xixilala.simple_use;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.GestureDescription;
import android.graphics.Path;
import android.graphics.Rect;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import java.util.List;

public class InstallerHelperService extends AccessibilityService {
    public static boolean isAlive = false;

    public static final String KEY_APP_INSTALLED = "key_app_installed";
    public static final String KEY_CLIP_BOARD    = "key_clip_board";


    private boolean appInstallPermissionDone = false;
    private boolean clipBoardPermissionDone = false;

    private boolean allowScroll = false;

    public static final int[] TAG_MENU_POSITION = {950,150}; //右上角点点点是按钮，但是没有文本，也无法根据id找到，故用座标代替
    public static final String TAG_SCROLL2MANAGER = "滑动到管理";
    public static final String TAG_ALL_REJECT = "全部拒绝";

    @Override
    public void onCreate() {
        super.onCreate();
        isAlive = true;
        MyAppInstallStats.addInstallAppReceiver(this);
    }

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        isAlive = true;
    }

    @Override
    public void onDestroy() {
        MyAppInstallStats.closeInstallAppReceiver(this);
        super.onDestroy();
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        AccessibilityNodeInfo rootNode = getRootInActiveWindow();
        if (rootNode == null) return;

        appInstallPermissionDone = (boolean) SharePreferencesUtils.getParam(this, KEY_APP_INSTALLED,false);
        clipBoardPermissionDone = (boolean) SharePreferencesUtils.getParam(this, KEY_CLIP_BOARD,false);

        if(clipBoardPermissionDone && appInstallPermissionDone) {
            return;
        }
        findAndClickView(rootNode);
    }

    private void findAndClickView(AccessibilityNodeInfo rootNode) {


        List<AccessibilityNodeInfo> findList;
        String key = "保护隐私数据信息";
        findList = rootNode.findAccessibilityNodeInfosByText(key);
        if (findList.size()>0) {
            performClick(key,findList);
            return;
        }

        key = TAG_SCROLL2MANAGER;
        findList = rootNode.findAccessibilityNodeInfosByText(key);
        if (findList.size()>0) {
            scroll(800,500, 300,500);
            return;
        }

        key = "查看所有权限使用状态";
        findList = rootNode.findAccessibilityNodeInfosByText(key);
        if (findList.size()>0) {
            performClick(key,findList);
            return;
        }

        if (!appInstallPermissionDone) {

            key = "获取手机中已安装的应用信息";
            findList = rootNode.findAccessibilityNodeInfosByText(key);
            if (findList.size() > 0) {
                performClick(key, findList);
                return;
            }


            key = "读取应用列表"; // 右上角
            findList = rootNode.findAccessibilityNodeInfosByText(key);

            if (findList.size() > 0) {
                forceClickXY(TAG_MENU_POSITION[0], TAG_MENU_POSITION[1]);
                return;
            }


            key = TAG_ALL_REJECT; //
            findList = rootNode.findAccessibilityNodeInfosByText(key);
            List<AccessibilityNodeInfo> findListConfirm = rootNode.findAccessibilityNodeInfosByText("确定");
            if (findList.size() > 0 && findListConfirm.size() == 0) {
                performClick(key, findList);
                return;
            }

            key = "确定"; //
            findList = rootNode.findAccessibilityNodeInfosByText(key);
            if (findList.size() > 0) {
                performClick(key, findList);
                performGlobalAction(GLOBAL_ACTION_BACK);
                appInstallPermissionDone = true;
                SharePreferencesUtils.setParam(this, InstallerHelperService.KEY_APP_INSTALLED,true);
                allowScroll = true;
                return;
            }
        }

        if (allowScroll) {
            allowScroll = false;
            key = "权限管理";
            findList = rootNode.findAccessibilityNodeInfosByText(key);
            if (findList.size() > 0) {
                scroll(500, 2000, 500, 1200);
                return;
            }
        }


        //剪切板
        if (!clipBoardPermissionDone) {

            key = "允许应用读写剪切板";
            findList = rootNode.findAccessibilityNodeInfosByText(key);
            if (findList.size() > 0) {
                performClick(key, findList);
                return;
            }

            key = "剪切板"; // 右上角
            findList = rootNode.findAccessibilityNodeInfosByText(key);
            if (findList.size() > 0) {
                forceClickXY(TAG_MENU_POSITION[0], TAG_MENU_POSITION[1]);
                return;
            }

            key = TAG_ALL_REJECT; //
            findList = rootNode.findAccessibilityNodeInfosByText(key);
            List<AccessibilityNodeInfo> findListConfirm = rootNode.findAccessibilityNodeInfosByText("确定");
            if (findList.size() > 0 && findListConfirm.size() == 0) {
                performClick(key, findList);
                return;
            }

            key = "确定"; //
            findList = rootNode.findAccessibilityNodeInfosByText(key);
            if (findList.size() > 0) {
                performClick(key, findList);
                clipBoardPermissionDone = true;
                SharePreferencesUtils.setParam(this, InstallerHelperService.KEY_CLIP_BOARD,true);

                performGlobalAction(GLOBAL_ACTION_HOME);
            }
        }
    }

    private void performClick(String key , List<AccessibilityNodeInfo> findList) {

        for (AccessibilityNodeInfo nodeInfo : findList) {

            if (key.contentEquals(nodeInfo.getText())) {

                boolean nodePerformClickResult = nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                boolean nodeParentPerformClickResult;
                if (!nodePerformClickResult) {
                    AccessibilityNodeInfo parentNode = nodeInfo.getParent();
                    if (parentNode == null) {
                        parentNode = nodeInfo;
                    }
                    nodeParentPerformClickResult = parentNode.performAction(AccessibilityNodeInfo.ACTION_CLICK);

                    if (!nodeParentPerformClickResult) {
                        forceClick(parentNode);
                    }
                }

            }
        }
    }

    private final GestureResultCallback gestureResultCallback = new GestureResultCallback() {
        @Override
        public void onCompleted(GestureDescription gestureDescription) {
            super.onCompleted(gestureDescription);

        }

        @Override
        public void onCancelled(GestureDescription gestureDescription) {
            super.onCancelled(gestureDescription);

        }
    };
    private void forceClick(AccessibilityNodeInfo nodeInfo) {

        int x, y;
        Rect px = new Rect();
        nodeInfo.getBoundsInScreen(px);
        x = px.left + 5;
        y = px.top + 5;

        GestureDescription.Builder builder = new GestureDescription.Builder();
        Path p = new Path();
        p.moveTo(x, y);
        builder.addStroke(new GestureDescription.StrokeDescription(p, 0L, 500L));
        GestureDescription gesture = builder.build();
        dispatchGesture(gesture, gestureResultCallback, null);

    }

    private void forceClickXY(int x, int y) {


        GestureDescription.Builder builder = new GestureDescription.Builder();
        Path p = new Path();
        p.moveTo(x, y);
        builder.addStroke(new GestureDescription.StrokeDescription(p, 0L, 500L));
        GestureDescription gesture = builder.build();
        dispatchGesture(gesture, gestureResultCallback, null);

    }

    private void scroll(int x0,int y0, int x1, int y1) {
        GestureDescription.Builder builder = new GestureDescription.Builder();
        Path p = new Path();
        p.moveTo(x0, y0);
        p.lineTo(x1, y1);
        builder.addStroke(new GestureDescription.StrokeDescription(p, 0L, 500L));
        GestureDescription gesture = builder.build();
        dispatchGesture(gesture, gestureResultCallback, null);
    }

    @Override
    public void onInterrupt() {
    }
}
